package htlgkr.nodlehs;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.ListView;
import android.widget.Toast;
import android.view.Menu;
import android.view.MenuInflater;

public class CreateNewTeacherActivity extends Activity {

	SQLiteDatabase db;
	NodlehsDatabase bridge;
	int help = 0;
	int index = 0;
	ArrayList<String> subAr;
	ListView lv;
	String first;
	String last;
	AutoCompleteTextView actv_last; 
	AutoCompleteTextView actv_first;
	long id = 0;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.newteacher);
		bridge = new NodlehsDatabase(this);
		db = bridge.getWritableDatabase();
		actv_first = (AutoCompleteTextView) findViewById(R.id.firstname);
		actv_last = (AutoCompleteTextView) findViewById(R.id.lastname);
	}	

	public void addTeacher(final View v) {
		addTeachertoDB();
		Log.i("NewTeacherActivity", first + "_" + last);
		Intent i = new Intent(v.getContext(), NODLEHSActivity.class);
		startActivity(i);
	}

	public void addTeachertoDB() {
		first = actv_first.getText().toString();
		last = actv_last.getText().toString();
		SQLiteStatement stmt = db.compileStatement(DBTeacherTbl.SQL_INSERT);
		db.beginTransaction();
		
		try {
			stmt.bindString(1, first);
			stmt.bindString(2, last);
			id = stmt.executeInsert();
			db.setTransactionSuccessful();

		} catch (Exception e) {
			Log.e("DBInsert Teacher", e.getMessage().toString());
		} finally {
			db.endTransaction();
		}
		Log.i("NewTeacherActivity", id + "");
	}
	public void addsubtoTeacher(final View v){
		Intent i = new Intent(v.getContext(), AddSubjectToTeacher.class);
		first = actv_first.getText().toString();
		last = actv_last.getText().toString();
		addTeachertoDB();
		Cursor teacher = db.query("teachers", DBTeacherTbl.ALL_COLUMNS, "tea_first_name = ? AND tea_last_name = ?", new String[]{first, last}, null, null, null);
		if(teacher.moveToFirst()){
			i.putExtra("Teacher_ID", teacher.getString(0));
			db.close();
			startActivityForResult(i, Activity.RESULT_CANCELED);
		}else Toast.makeText(this, "Invalid teacher ID", Toast.LENGTH_SHORT);
		
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.teachermenu, menu);
		return true;
	}
}
